package validators

import (
	"fox/request"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/locales"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	zh2 "github.com/go-playground/validator/v10/translations/zh"
)

var (
	Trans    ut.Translator
	Zh       locales.Translator
	Uni      *ut.UniversalTranslator
	Validate *validator.Validate
)

func InitValidateRegister() {
	var (
		v  *validator.Validate
		ok bool
	)

	Zh = zh.New()
	Uni = ut.New(Zh)
	Trans, _ = Uni.GetTranslator("zh")

	//注册中文
	Validate = binding.Validator.Engine().(*validator.Validate)
	zh2.RegisterDefaultTranslations(Validate, Trans)

	//注册自定义验证器
	if v, ok = binding.Validator.Engine().(*validator.Validate); ok {

		//手机验证
		v.RegisterValidation("MobileValida", request.MobileValida)
		v.RegisterTranslation("MobileValida", Trans, func(ut ut.Translator) error {
			return ut.Add("MobileValida", "{0}手机号有误", true)
		}, func(ut ut.Translator, fe validator.FieldError) string {
			t, _ := ut.T("MobileValida", fe.Field())
			return t
		})
	}
}

//Translate 翻译验证器里面的校验信息
func Translate(err error) string {
	var result string

	errors := err.(validator.ValidationErrors)

	for _, err := range errors {
		result = err.Translate(Trans)
	}
	return result
}
